package com.syp.auth.export.support.springmvc;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.syp.auth.export.common.GorgeousParameters;
import com.syp.auth.export.common.TokenCooikeMaster;
import com.syp.auth.export.request.TokenVerifyRequest;
import com.syp.auth.export.resource.AuthorizeResourceI;
import com.syp.auth.export.response.TokenVerifyResponse;
import com.syp.auth.export.util.SessionExcluder;

/**
 * session拦截器
 * 
 * @author syp
 * 
 */
public class SessionInterceptor implements HandlerInterceptor {

	private String authorizeBaseUrl;
	private String authorizeReturnUrl;
	private String app;
	private String[] excludeUriPatterns;
	private AuthorizeResourceI authorizeResource;

	/**
	 * 在调用controller具体方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (SessionExcluder.process(request, handler, excludeUriPatterns)) {
			return true;
		}

		Cookie token = TokenCooikeMaster.getInstunce().get(request);
		boolean unSignin = false;
		if (token != null) {
			// 验证token的有效性
			TokenVerifyRequest tvRequest = new TokenVerifyRequest();
			tvRequest.setToken(token.getValue());
			TokenVerifyResponse tvResponse = this.authorizeResource.verify(tvRequest);
			if (tvResponse.isValid()) {
				unSignin = false;
			} else {
				unSignin = true;
			}
		} else {
			unSignin = true;
		}
		if (unSignin) {
			token = TokenCooikeMaster.getInstunce().put(response);
			String suri = GorgeousParameters.buildSigninUri(this.authorizeBaseUrl, this.authorizeReturnUrl, token.getValue(), this.app);
			response.sendRedirect(suri);
			return false;
		}
		return true;
	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 完成页面的render后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

	public void setAuthorizeBaseUrl(String authorizeBaseUrl) {
		this.authorizeBaseUrl = authorizeBaseUrl;
	}

	public void setAuthorizeReturnUrl(String authorizeReturnUrl) {
		this.authorizeReturnUrl = authorizeReturnUrl;
	}

	public void setApp(String app) {
		this.app = app;
	}

	public void setExcludeUriPatterns(String[] excludeUriPatterns) {
		this.excludeUriPatterns = excludeUriPatterns;
	}

	public void setAuthorizeResource(AuthorizeResourceI authorizeResource) {
		this.authorizeResource = authorizeResource;
	}

}
